package com.itic.appbase.applications.exports;

import java.io.BufferedOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Map;
import java.util.Random;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;

import com.itic.appbase.framework.plugins.logger.Log;
/**
 * 导出Excel
 * <p>Company: itic</p>
 * @author: shijun
 * @date: 2015年6月1日 下午1:53:00
 * @version: V1.0
 */
public abstract class ExportExcel {
    
    protected Logger log = Log.get(getClass());//日志
    
    /**
     * 导出excel模板
     * @param mapConfig
     * @param response
     * @throws IOException
     */
    public void exportExcel(Map<String,Object> mapConfig,HttpServletRequest request,HttpServletResponse response) throws IOException{
        OutputStream  os = null;
        try {
            //清空resonance
            response.reset();
            os = new BufferedOutputStream(response.getOutputStream());
            //ServletOutputStream os = response.getOutputStream();
            // 设置下载文件的类型
            response.setContentType("application/vnd.ms-excel");
            // 随机生成下载的文件名
            Random random = new Random();
            String newpath = "file" + random.nextInt() + ".xls";
            response.setHeader("Content-Disposition", "attachment;filename=" + newpath);
            exportAutoExcel(mapConfig,request,os);//导出excel
            os.flush();
            os.close();
        } catch (Exception e) {
            String simplename = e.getClass().getSimpleName();
            log.info("导出excel发送异常，异常类型为："+simplename);
            if(!"ClientAbortException".equals(simplename)){
                throw new RuntimeException();
            }
        }finally{
            if(null!=os){
                os.close();
            }
        }
    }
    /**
     * 导出excel具体实现
     * @param mapConfig
     * @param outputStream
     */
    protected abstract void exportAutoExcel(Map<String,Object> mapConfig,HttpServletRequest request,OutputStream outputStream);
}
